package com.zhongxi.guoyuan.view.rewardCoin;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.AttrAdapter;
import com.zhongxi.guoyuan.adapter.BannerAdapter;
import com.zhongxi.guoyuan.adapter.coinShop.CoinPostGoodAttrAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinStore.AddToCart;
import com.zhongxi.guoyuan.entity.coinStore.AttrItemBean;
import com.zhongxi.guoyuan.entity.coinStore.AttrsSelect;
import com.zhongxi.guoyuan.entity.coinStore.CollectionBean;
import com.zhongxi.guoyuan.entity.coinStore.DouGoodsData;
import com.zhongxi.guoyuan.entity.coinStore.GoodsAttrCollections;
import com.zhongxi.guoyuan.entity.coinStore.RewardCoinDetailData;
import com.zhongxi.guoyuan.entity.user.center.MyInfo;
import com.zhongxi.guoyuan.fragment.RewardCoin.RewardCoinCommentFragment;
import com.zhongxi.guoyuan.fragment.RewardCoin.RewardCoinDetailFragment;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.HtmlActivity;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.shopCart.ShoppingCartActivity;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.widget.CircleIndicator;
import com.zhongxi.guoyuan.widget.ViewFlow;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class RewardCoinDetailActivity extends BaseActivity implements MyScrollView.OnScrollListener, View.OnClickListener {

//    private static final int REWARDCODE = 55;
    private ViewFlow myViewFlow;
    private BannerAdapter mBannerAdapter;
    private MyScrollView scrollView;
    private PopupWindow popupWindow;
    private View popupWindow_view;
    private RelativeLayout linearBottom;
    private LinearLayout linearLayout;
    private LinearLayout linearScrollBody;
    private LinearLayout linearBegin;
    private LinearLayout linearStop;
    private TextView tvGouwu;
    private TextView tvNature;

    private boolean isMeasured;
    private int mScrollHeight;
    private String goodsid;
    private String type;
    private TextView tvOrign;
    private LinearLayout tvgoshop;
    private TextView tvRest;
    private DouGoodsData douGoodsData;
    private LinearLayout btCollection;
    private LinearLayout tvShare;
    private Button[] tabs;
    private RewardCoinDetailFragment detailFragment;
    private RewardCoinCommentFragment commentFragment;
    private Fragment[] fragments;
    private Button btDetail;
    private Button btComment;
    private int index;
    private int currentIndex;
    private TextView tvName;
    private TextView tv_reward_price;
    private TextView tv_reward_yield;
    private TextView tv_reward_coin;
    private Map<String, String> map = new HashMap<>();
    private AttrAdapter adapter;
    private FrameLayout frame;
    private SHARE_MEDIA platform;
    private UMShareAPI mShareAPI;
    private CircleIndicator viewflowdic;
    private TextView tv_immediate_payment;
    private ImageView ivBack;
    private TextView tvTitle;
    private ImageView iv_shopCar;
    private List<GoodsAttrCollections> attrCollectionses;
    private RewardCoinDetailData goodsInfo;
    private JSONObject attr;
    private ArrayList<String> attrKeyList;
    private Map<String, List<String>> maps;
    private ArrayList<AttrsSelect> allList;
    private ImageView ivCollection;
    private List<List<AttrItemBean>> itemAttrList;
    private Map<String, List<AttrItemBean>> mapAllAttrs;
    private CoinPostGoodAttrAdapter coinPostGoodAttrAdapter;
    private boolean isSameAttrKey;
    private ImageView ivImg;
    private TextView tvInventory;
    private TextView tv_price;
    private TextView tv_yield;
    private TextView tv_coin;
    private TextView text_collect;
    private TextView redPaket_declare;

    boolean stateType1, stateType2, stateType3;  //同城,自提,邮寄
    private int mFlag;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_reward_coin_detail);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        iv_shopCar = (ImageView) findViewById(R.id.iv_shopCar);
        tvTitle.setText("线上赚豆商品详情");
        mShareAPI = UMShareAPI.get(this);
        goodsid = getIntent().getStringExtra("gid");
        mFlag = getIntent().getIntExtra("flag", 0);
        tvName = (TextView) findViewById(R.id.tvName);
        tv_reward_price = (TextView) findViewById(R.id.tv_reward_price);
        tv_reward_yield = (TextView) findViewById(R.id.tv_reward_yield);
        tv_reward_coin = (TextView) findViewById(R.id.tv_reward_coin);
        tvOrign = (TextView) findViewById(R.id.tvOrign);

        tvRest = (TextView) findViewById(R.id.tvRest);

        btCollection = (LinearLayout) findViewById(R.id.btCollection);
        ivCollection = (ImageView) findViewById(R.id.ivCollection);
        tvShare = (LinearLayout) findViewById(R.id.tvShare);
        tvgoshop = (LinearLayout) findViewById(R.id.tvgoshop);

        btDetail = (Button) findViewById(R.id.btDetail);
        btComment = (Button) findViewById(R.id.btComment);
        text_collect = (TextView) findViewById(R.id.text_collect);
        redPaket_declare= (TextView) findViewById(R.id.redPaket_declare);

        //上拉悬停
        scrollStop();

        //设置高度
        frame = (FrameLayout) findViewById(R.id.flow);
        ImageUtils.setHeight(this, Constants.detailRate, frame);
    }

    private void initViewPager() {
        tabs = new Button[2];
        tabs[0] = btDetail;
        tabs[1] = btComment;
        tabs[0].setSelected(true);
        detailFragment = new RewardCoinDetailFragment(goodsid, goodsInfo.getDesc());
        commentFragment = new RewardCoinCommentFragment(goodsid);
        fragments = new Fragment[]{detailFragment, commentFragment};
        getSupportFragmentManager().beginTransaction()
                .add(R.id.relaContainer, detailFragment).hide(commentFragment).commit();
    }

    @Override
    protected void initData() {
        super.initData();
        type = "details";
        String str = "&gid=" + goodsid;
        getServer(Url.MALL_GOODS_DETAILS, null, str, false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        iv_shopCar.setOnClickListener(this);
        tvGouwu.setOnClickListener(this);
        tvgoshop.setOnClickListener(this);
        tvNature.setOnClickListener(this);
        tv_immediate_payment.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        btDetail.setOnClickListener(this);
        btComment.setOnClickListener(this);
        redPaket_declare.setOnClickListener(this);

        btCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //收藏
                getCollection();
            }
        });
        //分享
        tvShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //分享
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    initPopuWindow();
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (4 == mFlag) {
            startAct(MainHomeActivity.class);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                if (4 == mFlag) {
                    startAct(MainHomeActivity.class);
                }
                break;
            case R.id.tvNature:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    getPopupWindow(0);
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.tvGouwu:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    getPopupWindow(1);
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.tv_immediate_payment:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    getPopupWindow(2);
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.tvgoshop:   //商家详情页
                Intent shopCarIntent = new Intent(context, RewardCoinShoperAtivity.class);
                shopCarIntent.putExtra("shopid", goodsInfo.getSid());
                startActivity(shopCarIntent);
                break;
            case R.id.iv_shopCar:   //购物车
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    Intent intent = new Intent(context, ShoppingCartActivity.class);
                    startActivity(intent);
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.btDetail:
                index = 0;
                if (linearScrollBody.getParent() == linearStop) {
                    linearStop.removeView(linearScrollBody);
                    linearBegin.addView(linearScrollBody);
                }
                break;
            case R.id.btComment:
                index = 1;
                if (linearScrollBody.getParent() == linearStop) {
                    linearStop.removeView(linearScrollBody);
                    linearBegin.addView(linearScrollBody);
                }
                break;
            case R.id.redPaket_declare:
                Intent intent = new Intent(RewardCoinDetailActivity.this, HtmlActivity.class);
                intent.putExtra("type", "consumeRule");
                startActivity(intent);
                break;
        }
        if (index != currentIndex) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            if (fragments[currentIndex].isAdded()) {
                trx.hide(fragments[currentIndex]);
            }
            if (!fragments[index].isAdded()) {
                trx.add(R.id.relaContainer, fragments[index]);
            }
            trx.show(fragments[index]).commit();
            tabs[index].setSelected(true);
            tabs[currentIndex].setSelected(false);
            currentIndex = index;
        }
    }

    /**
     * 收藏
     */
    private void getCollection() {
        if (!MyTextUtils.isFastDoubleClick()) {
            map.clear();
            map.put("ftype", "2");
            map.put("refid", goodsid);
            type = "collection";
            getServer(Url.ADD_FAVORITE, map, "", false, null, "post");
        }
    }

    /**
     * 弹出分享界面
     */
    private void initPopuWindow() {
        View popupWindow_view = getLayoutInflater().inflate(R.layout.pop_shared, null, false);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(tvShare, Gravity.BOTTOM, 0, 0);
        TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
        LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
        LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
        LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
        LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
        View.OnClickListener shareClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_qq:
                        platform = SHARE_MEDIA.QQ;
                        break;
                    case R.id.ll_wechat:
                        platform = SHARE_MEDIA.WEIXIN;
                        break;
                    case R.id.ll_qzone:
                        platform = SHARE_MEDIA.QZONE;
                        break;
                    case R.id.ll_friendscircle:
                        platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                        break;
                }

                UMWeb mUMWeb = new UMWeb(Url.IMG_URL + "/Home/pars/offline_get_url?id=" + goodsid);
                mUMWeb.setTitle("正常消费，额外再获一倍奖励=免费购物!");
                mUMWeb.setDescription("推荐一个好商品;正常消费,额外获豆豆,红豆可提现！");
                mUMWeb.setThumb(new UMImage(RewardCoinDetailActivity.this, R.mipmap.logo));
                new ShareAction(RewardCoinDetailActivity.this).setPlatform(platform)
                        .setCallback(umShareListener)
                        .withMedia(mUMWeb)
                        .share();
                popupWindow.dismiss();
            }
        };
        ll_qq.setOnClickListener(shareClickListener);
        ll_wechat.setOnClickListener(shareClickListener);
        ll_qzone.setOnClickListener(shareClickListener);
        ll_friendscircle.setOnClickListener(shareClickListener);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                showShortToast("收藏成功啦");
            } else {
                showShortToast("分享成功啦");
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showShortToast("分享取消了");
        }
    };

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("details".equals(type)) {
                douGoodsData = gson.fromJson(response, DouGoodsData.class);
                if (douGoodsData.getSafeobj() != null && !"".equals(douGoodsData.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(douGoodsData.getSafeobj());
                }
                if (douGoodsData.getGoodsAttrCollection() != null && !"".equals(douGoodsData.getGoodsAttrCollection())) {
                    attrCollectionses = douGoodsData.getGoodsAttrCollection();
                }
                if (douGoodsData.getGoodsInfo() != null && !"".equals(douGoodsData.getGoodsInfo())) {
                    goodsInfo = douGoodsData.getGoodsInfo();
                    if (goodsInfo.getImages() != null && goodsInfo.getImages().size() > 0) {
                        List<String> images = goodsInfo.getImages();
                        lunBo(images);
                    }
                    setDetails(goodsInfo);
                    initViewPager();
                    //初始化详情数据
                    detailFragment.initProjectData(goodsInfo.getCateid());
                }
                JSONObject jsonObject = new JSONObject(response);
                attr = jsonObject.optJSONObject("attrList");
                JSONArray attrKeyjson = jsonObject.optJSONArray("attrKey");//  "["汽车型号","形状","汽油型号","汽车牌照"]"
                attrKeyList = new ArrayList<>();
                for (int i = 0; i < attrKeyjson.length(); i++) {
                    String e = (String) attrKeyjson.get(i);
                    attrKeyList.add(e);
                }
                maps = new HashMap<>();
                if (attr != null && !"".equals(attr)) {
                    Iterator<String> keys = attr.keys();
                    while (keys.hasNext()) {
                        String next = keys.next();
                        JSONArray jsonArray = attr.optJSONArray(next);
                        List<String> attrIdList = new ArrayList<>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            try {
                                JSONArray jsonArray1 = (JSONArray) jsonArray.get(i);
                                for (int j = 0; j < jsonArray1.length(); j++) {
                                    if (j == 1) {
                                        String attrid = (String) jsonArray1.get(1);
                                        attrIdList.add(attrid);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        maps.put(next, attrIdList);
                    }
                }
                allList = new ArrayList<>();
                JSONArray jsonArray2 = jsonObject.optJSONArray("goodsAttrCollection");
                for (int i = 0; i < jsonArray2.length(); i++) {
                    JSONObject jsonObject1 = (JSONObject) jsonArray2.get(i);
                    AttrsSelect attrsSelect = new AttrsSelect();
                    String price = jsonObject1.optString("price");
                    String thumbnail = jsonObject1.optString("thumbnail");
                    String goodsid = jsonObject1.optString("goodsid");
                    String id = jsonObject1.optString("id");
                    String stocknum = jsonObject1.optString("stocknum");
                    JSONObject object = jsonObject1.optJSONObject("newattr");
                    Map<String, List<String>> itemAttrMap = new HashMap<>();
                    if (object != null && !"".equals(object)) {
                        Iterator<String> keys = object.keys();
                        while (keys.hasNext()) {
                            String next = keys.next();
                            JSONArray jsonArray = object.optJSONArray(next);
                            List<String> attr = new ArrayList<>();
                            if (jsonArray != null && jsonArray.length() > 0) {
                                for (int j = 0; j < jsonArray.length(); j++) {
                                    attr.add((String) jsonArray.get(j));
                                }
                                itemAttrMap.put(next, attr);
                            }
                        }
                    }
                    attrsSelect.setPrice(price);
                    attrsSelect.setThumbnail(thumbnail);
                    attrsSelect.setItemMaps(itemAttrMap);
                    attrsSelect.setGoodsid(goodsid);
                    attrsSelect.setId(id);
                    attrsSelect.setStocknum(stocknum);
                    attrsSelect.setShopName(douGoodsData.getShopInfo().getName());
                    attrsSelect.setShopId(douGoodsData.getShopInfo().getId());
                    attrsSelect.setPhone(douGoodsData.getShopInfo().getPhone());
                    attrsSelect.setAddress(douGoodsData.getShopInfo().getAddress());
                    attrsSelect.setAmountofmail(douGoodsData.getShopInfo().getAmountofmail());
                    allList.add(attrsSelect);
                }
            } else if ("goShoppingCart".equals(type)) {
                AddToCart addToCart = gson.fromJson(response, AddToCart.class);
                MyApplication.getInstance().setSpValue(addToCart.getSafeobj());
                showShortToast("添加购物车成功");
                popupWindow.dismiss();
                isRemove = false;
                popupWindow = null;
            } else if ("collection".equals(type)) {
                CollectionBean collectionBean = gson.fromJson(response, CollectionBean.class);
                if (null != collectionBean && !"".equals(collectionBean)) {
                    MyApplication.getInstance().setSpValue(collectionBean.getSafeobj());
                }
                ivCollection.setImageResource(R.mipmap.iv_hascollect);
                showShortToast("收藏成功！");
                text_collect.setText("已收藏");
                text_collect.setTextColor(getResources().getColor(R.color.red));
            } else if ("myinfo".equals(type)) {
                MyInfo myInfo = gson.fromJson(response, MyInfo.class);
                if (null != myInfo.getSafeobj() && !"".equals(myInfo.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(myInfo.getSafeobj());
                }
                if (null != myInfo.getUserInfo() && !"".equals(myInfo.getUserInfo())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", "1".equals(myInfo.getUserInfo().getIsshareholders())).commit();
                }
                if (String.valueOf(myInfo.getSharesnum()) != null) {
                    MyApplication.getInstance().sharedPrefrences.edit().putInt("point", myInfo.getSharesnum()).commit();
                }
                if ((null != String.valueOf(myInfo.getInnernum()) && myInfo.getInnernum() > 0)
                        || (null != myInfo.getRedbeannum() && DataUtil.moreThanOtherNoEqual(myInfo.getRedbeannum(), "0"))) {
                    showGetBackSilverDialog(myInfo.getInnernum(), myInfo.getRedbeannum());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 活动返现
     *
     * @param backSilver
     * @param redbeannum
     */
    private void showGetBackSilverDialog(int backSilver, String redbeannum) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dialog_back_silver, null);
//        View view = View.inflate(this, R.layout.dialog_back_silver, null);
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        ImageView ivCancle = (ImageView) view.findViewById(R.id.iv_back_cancle);
        TextView tv_HD_number = (TextView) view.findViewById(R.id.tv_HD_number);
        TextView tv_MD_number = (TextView) view.findViewById(R.id.tv_MD_number);

        if (backSilver > 0 && DataUtil.moreThanOtherNoEqual(redbeannum, "0")) {
            tv_HD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setVisibility(View.VISIBLE);
            tv_HD_number.setText(redbeannum + "  红豆");
            tv_MD_number.setText(backSilver + "  美豆");
        } else if (backSilver > 0 && !DataUtil.moreThanOtherNoEqual(redbeannum, "0")) {
            tv_HD_number.setVisibility(View.GONE);
            tv_MD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setText(backSilver + "  美豆");
        } else if (backSilver <= 0 && DataUtil.moreThanOtherNoEqual(redbeannum, "0")) {
            tv_HD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setVisibility(View.GONE);
            tv_HD_number.setText(redbeannum + "  红豆");
        } else {
            tv_HD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setVisibility(View.VISIBLE);
            tv_HD_number.setText("0  红豆");
            tv_MD_number.setText("0  美豆");
        }
        TextView tvSure = (TextView) view.findViewById(R.id.tv_back_silver_sure);
        ivCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
                if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void lunBo(List<String> images) {
        myViewFlow = (ViewFlow) findViewById(R.id.viewflow);
        viewflowdic = (CircleIndicator) findViewById(R.id.viewflowdic);
        myViewFlow.setFlowIndicator(viewflowdic);
        myViewFlow.setSideBuffer(images.size()); // 实际图片数量
        if (mBannerAdapter == null) {
            mBannerAdapter = new BannerAdapter(context, images);
        } else {
            mBannerAdapter.replaceAll(images);
        }
        myViewFlow.setAdapter(mBannerAdapter);
        myViewFlow.startAutoFlowTimer();
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if (1000 == result.getCode()) {
                finish();
            }
            if (1001 == result.getCode()) {
                showShortToast("用户未登录，请先登录");
            } else if (1201 == result.getCode()) {
                showShortToast("店铺关闭");
                finish();
            } else if (1557 == result.getCode()) {
                showShortToast("数量超限");
            } else if (2000 == result.getCode()) {
                showShortToast("商品信息不完整");
                finish();
            } else if (2001 == result.getCode()) {
                showShortToast("商品库存不足");
            } else if (2005 == result.getCode()) {
                showShortToast("商品与 商品集合不匹配");
            } else if (2006 == result.getCode()) {
                showShortToast("商品集合数据格式错误");
            } else if (2007 == result.getCode()) {
                showShortToast("商品属性不在指定集合中");
            } else if (2008 == result.getCode()) {
                showShortToast("商品属性数据丢失， 请管理员调整");
            } else if (2009 == result.getCode()) {
                showShortToast("商品属性选择不完整");
            } else if (5000 == result.getCode()) {
                showShortToast("商品信息不完善");
                finish();
            } else if (1000 == result.getCode()) {
                showShortToast("参数错误");
                finish();
            } else if (5001 == result.getCode()) {
                showShortToast("店铺已关闭");
                finish();
            } else if (5002 == result.getCode()) {
                showShortToast("集合信息丢失， 请重试");
            } else if (5003 == result.getCode()) {
                showShortToast("集合信息不完整， 请联系管理员修正");
            } else if (5004 == result.getCode()) {
                showShortToast("商品属性 不是有效集合");
            } else if (5005 == result.getCode()) {
                showShortToast("单件商品数量超限");
            } else if (5006 == result.getCode()) {
                showShortToast("购物车商品数量超限");
            } else if (1682 == result.getCode()) {
                ivCollection.setImageResource(R.mipmap.iv_hascollect);
                text_collect.setText("已收藏");
                text_collect.setTextColor(getResources().getColor(R.color.red));
                showShortToast("该项目已收藏");
            } else if (5019 == result.getCode()) {
                showShortToast("选购商品数量超过库存");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 商品详细
     *
     * @param goodsInfos
     */
    private void setDetails(RewardCoinDetailData goodsInfos) {
        try {
            if (null != goodsInfos.getName() && !"".equals(goodsInfos.getName())) {
                tvName.setText(goodsInfos.getName());
            } else {
                tvName.setText("");
            }
            if (TextUtils.isEmpty(goodsInfos.getFloorprice()) && TextUtils.isEmpty(goodsInfos.getPeakprice())) {
                tv_reward_price.setText("0 元");
            } else {
                if (goodsInfos.getFloorprice().equals(goodsInfos.getPeakprice())) {
                    tv_reward_price.setText(goodsInfos.getFloorprice() + " 元");
                } else {
                    tv_reward_price.setText(goodsInfos.getFloorprice() + "~" + goodsInfos.getPeakprice() + " 元");
                }
            }

            switch (goodsInfos.getGoodstype()) {
                case 1:
                    if (TextUtils.isEmpty(goodsInfos.getFloorprice()) && TextUtils.isEmpty(goodsInfos.getPeakprice())) {
                        tv_reward_coin.setText("");
                        tv_reward_yield.setText("");
                    } else {
                        String mSubstring = CommonTool.getWhole(goodsInfos.getFloorprice());
                        if (DataUtil.multiplys(goodsInfos.getFloorprice(), "0.05", 2).equals(DataUtil.multiplys(goodsInfos.getPeakprice(), "0.05", 2))) {
                            tv_reward_coin.setText(context.getResources().getString(R.string.give_meidou) + mSubstring + "美豆");
                            if (DataUtil.moreThanZero((DataUtil.multiplys(goodsInfos.getFloorprice(), "0.05", 2)))){
                                tv_reward_yield.setText(context.getResources().getString(R.string.more_give) + CommonTool.getWhole(DataUtil.multiplys(goodsInfos.getFloorprice(), "0.1", 2)) + "红豆");

                            }else{
                                tv_reward_yield.setVisibility(View.GONE);

                            }
                        } else {
                            String mSubstring1 = CommonTool.getWhole(goodsInfos.getPeakprice());

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                tv_reward_coin.setText(Html.fromHtml("<font color=\"#ff7f00\">" + context.getResources().getString(R.string.give_meidou) + mSubstring +
                                        "~" + mSubstring1 + "美豆</font>", Html.FROM_HTML_MODE_COMPACT));

                                tv_reward_yield.setText(Html.fromHtml("<font color=\"#ff4c4c\">" + context.getResources().getString(R.string.more_give) + DataUtil.multiplys(goodsInfos.getFloorprice(), "0.05", 2) + "~"
                                        + DataUtil.multiplys(goodsInfos.getPeakprice(), "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));
                            } else {
                                tv_reward_coin.setText(Html.fromHtml("<font color=\"#ff7f00\">" + context.getResources().getString(R.string.give_meidou) + mSubstring +
                                        "~" + mSubstring1 + "美豆</font>"));

                                tv_reward_yield.setText(Html.fromHtml("<font color=\"#ff4c4c\">" + context.getResources().getString(R.string.more_give) + DataUtil.multiplys(goodsInfos.getFloorprice(), "0.05", 2) + "~"
                                        + DataUtil.multiplys(goodsInfos.getPeakprice(), "0.05", 2) + "红豆</font>"));
                            }

                         /*   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                tv_reward_coin.setText(Html.fromHtml("<font color=\"#ff7f00\">" + context.getResources().getString(R.string.give_meidou) + mSubstring +
                                        "美豆<br/></font><font color=\"#ff4c4c\">" + context.getResources().getString(R.string.more_give)+ DataUtil.multiplys(goodsInfos.getFloorprice(), "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));
                                tv_reward_yield.setText(Html.fromHtml("<font color=\"#ff7f00\"> ~ " + mSubstring1 + "美豆<br/></font><font color=\"#ff4c4c\">"
                                        + context.getResources().getString(R.string.more_give)+ DataUtil.multiplys(goodsInfos.getPeakprice(), "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));
                            } else {
                                tv_reward_coin.setText(Html.fromHtml("<font color=\"#ff7f00\">" +
                                        context.getResources().getString(R.string.give_meidou) + mSubstring +
                                        "美豆<br/></font><font color=\"#ff4c4c\">"+ context.getResources().getString(R.string.more_give) + DataUtil.multiplys(goodsInfos.getFloorprice(), "0.05", 2) + "红豆</font>"));

                                tv_reward_yield.setText(Html.fromHtml("<font color=\"#ff7f00\"> ~ " + mSubstring1 +
                                        "美豆<br/></font><font color=\"#ff4c4c\">" + context.getResources().getString(R.string.more_give)+ DataUtil.multiplys(goodsInfos.getPeakprice(), "0.05", 2) + "红豆</font>"));
                            }*/
                        }
                    }
                    break;
//                case 2:
//                    if (goodsInfos.getFloorprice().equals(goodsInfos.getPeakprice())) {
//                        tv_reward_coin.setText("立即赠 " + DataUtil.multiplys(goodsInfos.getFloorprice(), "2") + " 美豆");
//                    } else {
//                        tv_reward_coin.setText("立即赠" + DataUtil.multiplys(goodsInfos.getFloorprice(), "2") + "美豆 ~ " + DataUtil.multiplys(goodsInfos.getPeakprice(), "2") + "美豆");
//                    }
//                    break;
                case 3:
                    if (TextUtils.isEmpty(goodsInfos.getFloorprice()) && TextUtils.isEmpty(goodsInfos.getPeakprice())) {
                        tv_reward_coin.setText("");
                        tv_reward_yield.setText("");
                    } else {
                        tv_reward_yield.setTextColor(context.getResources().getColor(R.color.title_red));
                        tv_reward_coin.setTextColor(context.getResources().getColor(R.color.title_red));

                        if (CommonTool.getWhole(DataUtil.multiplys(goodsInfos.getFloorprice(), Constants.REDBEAN_RATE, 4)).equals(CommonTool.getWhole(DataUtil.multiplys(goodsInfos.getPeakprice(), Constants.REDBEAN_RATE, 4)))) {
                            if (DataUtil.moreThanZero(CommonTool.getWhole((DataUtil.multiplys(goodsInfos.getFloorprice(), Constants.REDBEAN_RATE, 4))))){
                                tv_reward_yield.setText(getString(R.string.award_hongdou) + CommonTool.getWhole(DataUtil.multiplys(goodsInfos.getFloorprice(), Constants.REDBEAN_RATE, 4)) + " 红豆");
                            }else{
                                tv_reward_yield.setVisibility(View.GONE);
                            }

                        }else {
                            if (DataUtil.moreThanZero(CommonTool.getWhole(DataUtil.multiplys(goodsInfos.getPeakprice(), Constants.REDBEAN_RATE, 4)))){
                                tv_reward_yield.setText(getString(R.string.award_hongdou) +
                                        CommonTool.getWhole(DataUtil.multiplys(goodsInfos.getFloorprice(), Constants.REDBEAN_RATE, 4)) + "红豆 ~ " + CommonTool.getWhole(DataUtil.multiplys(goodsInfos.getPeakprice(), Constants.REDBEAN_RATE, 4)) + "红豆");
                            }else{
                                tv_reward_yield.setVisibility(View.GONE);
                            }
                        }
                        if (goodsInfo.getFloorprice().equals(goodsInfos.getPeakprice())){
                            tv_reward_coin.setText(getResources().getString(R.string.goldenDesc) + goodsInfos.getFloorprice() + "元消费红包 ");
                        }else {
                            tv_reward_coin.setText(getResources().getString(R.string.goldenDesc) + goodsInfos.getFloorprice() + "元 ~ " + goodsInfos.getPeakprice() + " 元消费红包");

                        }

                    }
                    break;
            }
            if (null != goodsInfos.getMarketprice() && !"".equals(goodsInfos.getMarketprice())) {
                tvOrign.setText("市场价：" + goodsInfos.getMarketprice() + " 元");
                tvOrign.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            } else {
                tvOrign.setText("市场价：0 元");
                tvOrign.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            }

            if (null != goodsInfos.getOrdernum() && !"".equals(goodsInfos.getOrdernum())) {
                tvRest.setText(goodsInfos.getOrdernum());
            } else {
                tvRest.setText("0");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void scrollStop() {
        scrollView = (MyScrollView) findViewById(R.id.scrollView);
        linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
        linearScrollBody = (LinearLayout) findViewById(R.id.linearScrollBody);
        linearBegin = (LinearLayout) findViewById(R.id.linearBegin);
        linearStop = (LinearLayout) findViewById(R.id.linearStop);
        linearBottom = (RelativeLayout) findViewById(R.id.linearBottom);
        tvGouwu = (TextView) findViewById(R.id.tvGouwu);
        tvNature = (TextView) findViewById(R.id.tvNature);
        tv_immediate_payment = (TextView) findViewById(R.id.tv_immediate_payment);
        scrollView.setOnScrollListener(this);
        ViewTreeObserver observer = linearLayout.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isMeasured) {
                    mScrollHeight = linearLayout.getMeasuredHeight();
                    isMeasured = true;
                }
                return true;
            }
        });
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= mScrollHeight) {
            if (linearScrollBody.getParent() != linearStop) {
                linearBegin.removeView(linearScrollBody);
                linearBegin.setLayoutParams(new LinearLayout.LayoutParams(linearScrollBody.getMeasuredWidth(), linearScrollBody.getMeasuredHeight()));
                linearStop.addView(linearScrollBody);
            }
        } else {
            if (linearScrollBody.getParent() != linearBegin) {
                linearStop.removeView(linearScrollBody);
                linearBegin.addView(linearScrollBody);
            }
        }
    }

    @Override
    public void scrollBottom() {
    }

    private void getPopupWindow(int i) {
        if (null != popupWindow && popupWindow.isShowing()) {
            popupWindow.dismiss();
            return;
        } else {
            initAttrPopupWindow(i);
        }
    }

    boolean isRemove = false;

    private void initAttrPopupWindow(final int flag) {
        final Map<String, AttrItemBean> selectAttrMap = new HashMap<>();
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                AttrItemBean attrItemBean = (AttrItemBean) msg.getData().getSerializable("attrItemBean");
                String attrId = attrItemBean.getAttrId();
                for (String attrKey : maps.keySet()) {
                    List<String> list = maps.get(attrKey);
                    for (int i = 0; i < list.size(); i++) {
                        if (attrId.equals(list.get(i))) {  //找到相应的key
                            if (selectAttrMap != null) {
                                if (selectAttrMap.size() > 0) {
                                    Iterator<String> iterator = selectAttrMap.keySet().iterator();
                                    while (iterator.hasNext()) {
                                        String next = iterator.next();
                                        AttrItemBean mapValue = selectAttrMap.get(next);
                                        if (mapValue.getAttrId().equals(attrId)) {   //去除属性
                                            iterator.remove();
                                            isRemove = true;
                                            break;
                                        }
                                    }
                                    if (isRemove) {  //去除属性
                                        if (selectAttrMap.size() > 0) {
                                            if (selectAttrMap.size() == 1) {
                                                Map.Entry<String, AttrItemBean> next = selectAttrMap.entrySet().iterator().next();
                                                String key = next.getKey();
                                                AttrItemBean value = next.getValue();
                                                List<String> canAttrs = getOnlyOneAttrCanSelect(value, key);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                isRemove = false;
                                                getItemClickChangePic();
                                                return;
                                            } else {
                                                List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                                List<String> listStrings = getCompareStringList();
                                                referList.addAll(listStrings);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                isRemove = false;
                                                getItemClickChangePic();
                                                return;
                                            }
                                        } else {  //无点击,恢复正常
                                            itemAttrList = DataUtil.updataAdapter(itemAttrList);
                                            coinPostGoodAttrAdapter.notifyDataSetChanged();
                                            selectAttrMap.clear();
                                            isRemove = false;
                                            getItemClickChangePic();
                                            return;
                                        }
                                    } else {  //不去除属性
                                        for (String selectKey : selectAttrMap.keySet()) {
                                            if (attrKey.equals(selectKey)) {  //同一类点击切换
                                                isSameAttrKey = true;
                                                break;
                                            }
                                        }
                                        if (isSameAttrKey) {  //同一类点击切换
                                            if (selectAttrMap.size() == 1) {
                                                selectAttrMap.clear();
                                                selectAttrMap.put(attrKey, attrItemBean);
                                                List<String> canAttrs = getOnlyOneAttrCanSelect(attrItemBean, attrKey);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                getItemClickChangePic();
                                                isSameAttrKey = false;
                                                return;
                                            } else {
                                                selectAttrMap.put(attrKey, attrItemBean);
                                                List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                                List<String> listStrings = getCompareStringList();
                                                referList.addAll(listStrings);
                                                itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                                coinPostGoodAttrAdapter.notifyDataSetChanged();
                                                getItemClickChangePic();
                                                isSameAttrKey = false;
                                                return;
                                            }
                                        } else {  //不同类的属性点击
                                            selectAttrMap.put(attrKey, attrItemBean);
                                            List<String> referList = getAllAlreadItemCanSelect(selectAttrMap);
                                            List<String> listStrings = getCompareStringList();
                                            referList.addAll(listStrings);
                                            itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, referList, selectAttrMap);
                                            coinPostGoodAttrAdapter.notifyDataSetChanged();
                                            getItemClickChangePic();
                                            isSameAttrKey = false;
                                            return;
                                        }
                                    }
                                } else {
                                    selectAttrMap.put(attrKey, attrItemBean);
                                    List<String> canAttrs = getOnlyOneAttrCanSelect(attrItemBean, attrKey);
                                    itemAttrList = DataUtil.updataInfoUpgrade(itemAttrList, canAttrs, selectAttrMap);
                                    coinPostGoodAttrAdapter.notifyDataSetChanged();
                                    getItemClickChangePic();
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            @NonNull
            private List<String> getCompareStringList() {
                List<List<String>> compareOtherList = new ArrayList<>();
                for (String strKey : selectAttrMap.keySet()) {
                    Map<String, AttrItemBean> secordMap = new HashMap<>();
                    for (String secordKey : selectAttrMap.keySet()) {
                        if (!secordKey.equals(strKey)) {
                            secordMap.put(secordKey, selectAttrMap.get(secordKey));
                        }
                    }
                    List<String> secordItemList = getAllAlreadItemCanSelect(secordMap);
                    List<String> singleList = getSingleList(strKey);
                    List<String> itemAttrsList = new ArrayList<>();
                    for (int j = 0; j < secordItemList.size(); j++) {
                        if (singleList.contains(secordItemList.get(j))) {
                            itemAttrsList.add(secordItemList.get(j));
                        }
                    }
                    compareOtherList.add(itemAttrsList);
                }
                return getListStrings(compareOtherList);
            }

            @NonNull
            private List<String> getSingleList(String attrKey) {
                int indexInList = DataUtil.indexInList(attrKeyList, attrKey);
                List<String> singleList = new ArrayList<>();
                List<AttrItemBean> attrItemBeens = itemAttrList.get(indexInList);
                for (int j = 0; j < attrItemBeens.size(); j++) {
                    AttrItemBean itemBean = attrItemBeens.get(j);
                    singleList.add(itemBean.getAttrId());
                }
                return singleList;
            }

            private void getItemClickChangePic() {
                if (selectAttrMap != null && selectAttrMap.size() > 0) {
                    List<String> listId = new ArrayList<>();
                    for (String strKey : selectAttrMap.keySet()) {
                        AttrItemBean itemBean = selectAttrMap.get(strKey);
                        listId.add(itemBean.getAttrId());
                    }
                    List<GoodsAttrCollections> collectioneList = new ArrayList<>();
                    for (GoodsAttrCollections goodAttr : attrCollectionses) {
                        List<String> attrs = goodAttr.getAttrs();
                        if (attrs.containsAll(listId)) {
                            collectioneList.add(goodAttr);
                        }
                    }
                    if (collectioneList.get(0).getPrice() != null && !"".equals(collectioneList.get(0).getPrice())) {
                        tv_price.setText(collectioneList.get(0).getPrice() + " 元");
                    } else {
                        tv_price.setText("0 元");
                    }
                    switch (goodsInfo.getGoodstype()) {
                        case 1:
                            if (collectioneList.get(0).getPrice() != null && !"".equals(collectioneList.get(0).getPrice())) {
                                String mSubstring = CommonTool.getWhole(collectioneList.get(0).getPrice());
                                tv_coin.setText(context.getResources().getString(R.string.give_meidou) + mSubstring + " 美豆");
                                tv_yield.setText(context.getResources().getString(R.string.more_give) + DataUtil.multiplys(collectioneList.get(0).getPrice(), "0.05", 2) + " 红豆");
                                tv_coin.setTextColor(context.getResources().getColor(R.color.postCartItem));
                                tv_yield.setTextColor(context.getResources().getColor(R.color.title_red));
                            } else {
                                tv_coin.setText("");
                                tv_yield.setText("");
                            }
                            break;
//                        case 2:
//                            if (collectioneList.get(0).getPrice() != null && !"".equals(collectioneList.get(0).getPrice())) {
//                                tv_coin.setText("立即赠 " + DataUtil.multiplys(collectioneList.get(0).getPrice(), "2") + " 美豆");
//                            } else {
//                                tv_coin.setText("");
//                            }
//                            break;
                        case 3:
                            if (collectioneList.get(0).getPrice() != null && !"".equals(collectioneList.get(0).getPrice())) {
                                if (DataUtil.moreThanZero(CommonTool.getWhole(DataUtil.multiplys(collectioneList.get(0).getPrice(), Constants.REDBEAN_RATE, 4)))){
                                    tv_yield.setText(getResources().getString(R.string.award_hongdou) +CommonTool.getWhole(DataUtil.multiplys(collectioneList.get(0).getPrice(), Constants.REDBEAN_RATE, 4)) + "红豆");
                                    tv_yield.setTextColor(context.getResources().getColor(R.color.title_red));
                                }else {
                                    tv_yield.setText("");
                                }

                                tv_coin.setText(context.getResources().getString(R.string.goldenDesc) + collectioneList.get(0).getPrice() + " 元消费红包");
                                tv_coin.setTextColor(context.getResources().getColor(R.color.title_red));
                            } else {
                                tv_yield.setText("");
                                tv_coin.setText("");
                            }
                            break;
                    }

                    if (collectioneList.get(0).getStocknum() != null && !"".equals(collectioneList.get(0).getStocknum())) {
                        tvInventory.setText("库存:" + collectioneList.get(0).getStocknum() + "件");
                    } else {
                        tvInventory.setText("库存:0件");
                    }
                    Glide.with(context).load(Url.IMG_URL + collectioneList.get(0).getThumbnail()).placeholder(R.mipmap.iv_eg).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivImg);
                } else {
                    Glide.with(context).load(Url.IMG_URL + goodsInfo.getImages().get(0)).placeholder(R.mipmap.iv_eg).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivImg);
                    tvInventory.setText("库存:999件");
                }
            }

            @NonNull
            private List<String> getOnlyOneAttrCanSelect(AttrItemBean attrItemBean, String selectKey) {
                ArrayList<String> canSelects = getItemCanSelectAttr(attrItemBean);
                List<String> oneSelectCanAttr = new ArrayList<>();
                List<String> canAttrs = new ArrayList<>();
                for (String str : mapAllAttrs.keySet()) {
                    if (str.equals(selectKey)) {
                        List<AttrItemBean> attrItemBeenList = mapAllAttrs.get(str);
                        for (int j = 0; j < attrItemBeenList.size(); j++) {
                            oneSelectCanAttr.add(attrItemBeenList.get(j).getAttrId());
                        }
                    }
                }
                oneSelectCanAttr.addAll(canSelects);
                Set set = new HashSet();
                for (String str : oneSelectCanAttr) {
                    if (set.add(str)) {
                        canAttrs.add(str);  //去重后的可选的属性
                    }
                }
                return canAttrs;
            }

            @NonNull
            private List<String> getAllAlreadItemCanSelect(Map<String, AttrItemBean> selectAttrMap) {
                List<String> temporaryAttrId = new ArrayList<>();
                for (String str : selectAttrMap.keySet()) {
                    AttrItemBean attrBean = selectAttrMap.get(str);
                    temporaryAttrId.add(attrBean.getAttrId());
                }
                List<List<String>> collectionses = new ArrayList<>();
                for (GoodsAttrCollections goodAttr : attrCollectionses) {
                    List<String> attrs = goodAttr.getAttrs();
                    if (attrs.containsAll(temporaryAttrId)) {
                        collectionses.add(attrs);
                    }
                }
//                referList.addAll(collectionses.get(0));
//                for (int j = 0; j < collectionses.size(); j++) {
//                    referList.retainAll(collectionses.get(j));    //多数组取交集
//                }
                List<String> referList = getListStrings(collectionses);
                return referList;
            }

            @NonNull
            private List<String> getListStrings(List<List<String>> collectionses) {
                List<String> referList = new ArrayList<>();
                Set set = new HashSet();
                for (int i = 0; i < collectionses.size(); i++) {
                    List<String> list = collectionses.get(i);
                    for (int j = 0; j < list.size(); j++) {
                        if (set.add(list.get(j))) {
                            referList.add(list.get(j));
                        }
                    }
                }
                return referList;
            }

            @NonNull
            private ArrayList<String> getItemCanSelectAttr(AttrItemBean attrItemBean) {
                List<List<String>> collectionses = new ArrayList<>();
                for (GoodsAttrCollections goodAttr : attrCollectionses) {
                    if (goodAttr.getAttrs().contains(attrItemBean.getAttrId())) {
                        collectionses.add(goodAttr.getAttrs());
                    }
                }
                Set set = new HashSet();
                ArrayList<String> canSelects = new ArrayList<>();
                for (List<String> collection : collectionses) {
                    for (String attr : collection) {
                        if (set.add(attr)) {
                            canSelects.add(attr);
                        }
                    }
                }
                return canSelects;
            }
        };
        popupWindow_view = getLayoutInflater().inflate(R.layout.base_cart_info, null);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        ivImg = (ImageView) popupWindow_view.findViewById(R.id.ivImg);
        ImageView ivCancel = (ImageView) popupWindow_view.findViewById(R.id.ivCancel);
        TextView tvName = (TextView) popupWindow_view.findViewById(R.id.tvName);
        tvInventory = (TextView) popupWindow_view.findViewById(R.id.tvInventory);
        tv_price = (TextView) popupWindow_view.findViewById(R.id.tv_reward_price);
        tv_yield = (TextView) popupWindow_view.findViewById(R.id.tv_reward_yield);
        tv_coin = (TextView) popupWindow_view.findViewById(R.id.tv_reward_coin);
        TextView tvAdd = (TextView) popupWindow_view.findViewById(R.id.tvAdd);
        TextView tvSub = (TextView) popupWindow_view.findViewById(R.id.tvSub);
        final EditText etNum = (EditText) popupWindow_view.findViewById(R.id.etNum);
        final TextView tvAddSure_attr = (TextView) popupWindow_view.findViewById(R.id.tvAddSure_attr);
        TextView tvSure_attr = (TextView) popupWindow_view.findViewById(R.id.tvSure_attr);
        ListView lvList = (ListView) popupWindow_view.findViewById(R.id.lvList);
        final LinearLayout type1 = (LinearLayout) popupWindow_view.findViewById(R.id.cart_get_type1);  //当面付
        final TextView tv1 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv1);
        final TextView tv11 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv11);
        final LinearLayout type2 = (LinearLayout) popupWindow_view.findViewById(R.id.cart_get_type2);   //自提
        final TextView tv2 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv2);
        final TextView tv22 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv22);
        final LinearLayout type3 = (LinearLayout) popupWindow_view.findViewById(R.id.cart_get_type3);   //邮寄
        final TextView tv3 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv3);
        final TextView tv33 = (TextView) popupWindow_view.findViewById(R.id.cart_get_tv33);
        TextView tv_amountofmail = (TextView) popupWindow_view.findViewById(R.id.tv_amountofmail);
        if (douGoodsData.getShopInfo().getAmountofmail() != null && !"".equals(douGoodsData.getShopInfo().getAmountofmail())) {
            if (!"0".equals(douGoodsData.getShopInfo().getAmountofmail())) {
                tv_amountofmail.setText("本店满" + douGoodsData.getShopInfo().getAmountofmail() + "元包邮");
                tv33.setText("快递:" + goodsInfo.getPostage() + "元");
            } else if (!DataUtil.moreThanZero(goodsInfo.getPostage())) {
                tv_amountofmail.setText("本店商品包邮");
                tv33.setText("快递:" + goodsInfo.getPostage() + "元");
            } else {
                tv_amountofmail.setText("本店商品不包邮");
                tv33.setText("快递:" + goodsInfo.getPostage() + "元");
            }
        }
        RelativeLayout relative1 = (RelativeLayout) popupWindow_view.findViewById(R.id.relative1);
        RelativeLayout relative2 = (RelativeLayout) popupWindow_view.findViewById(R.id.relative2);
        WindowManager manger = (WindowManager) getSystemService(RewardCoinDetailActivity.WINDOW_SERVICE);
        Display display = manger.getDefaultDisplay();
        RelativeLayout rl_ctx = (RelativeLayout) popupWindow_view.findViewById(R.id.rl_ctx);
        ViewGroup.LayoutParams layoutParams = rl_ctx.getLayoutParams();
        layoutParams.height = 4 * display.getHeight() / 5;
        if (goodsInfo.getImages() != null && goodsInfo.getImages().size() > 0) {
            Glide.with(context).load(Url.IMG_URL + goodsInfo.getImages().get(0))
                    .placeholder(R.mipmap.iv_eg).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivImg);
        }
        tvName.setText(goodsInfo.getName());
        if (flag == 1) {
            tvAddSure_attr.setText("   确    定   ");
            relative1.setVisibility(View.VISIBLE);
            relative2.setVisibility(View.GONE);
        } else if (flag == 2) {
            tvSure_attr.setText("    确    定   ");
            relative1.setVisibility(View.GONE);
            relative2.setVisibility(View.VISIBLE);
        } else {
            tvAddSure_attr.setText("加入购物车");
            tvSure_attr.setText("  立即支付  ");
            relative1.setVisibility(View.VISIBLE);
            relative2.setVisibility(View.VISIBLE);
        }

        if (goodsInfo.getFloorprice().equals(goodsInfo.getPeakprice())) {
            tv_price.setText(goodsInfo.getFloorprice() + " 元");
        } else {
            tv_price.setText(goodsInfo.getFloorprice() + " ~ " + goodsInfo.getPeakprice() + "元");
        }
        switch (goodsInfo.getGoodstype()) {
            case 1:
                if (TextUtils.isEmpty(goodsInfo.getFloorprice())) {
                    tv_coin.setText("");
                    tv_yield.setText("");
                } else {
                    tv_coin.setTextColor(context.getResources().getColor(R.color.postCartItem));
                    String mSubstring = CommonTool.getWhole(goodsInfo.getFloorprice());
                    if (goodsInfo.getFloorprice().equals(goodsInfo.getPeakprice())) {
                        tv_coin.setText(context.getResources().getString(R.string.give_meidou) + mSubstring + " 美豆");
                        tv_yield.setText(context.getResources().getString(R.string.more_give) + DataUtil.multiplys(goodsInfo.getFloorprice(), "0.05", 2) + "红豆");
                    } else {
                        String mSubstring1 = CommonTool.getWhole(goodsInfo.getPeakprice());
                        tv_coin.setText(context.getResources().getString(R.string.give_meidou) + mSubstring + "美豆 ~ " + mSubstring1 + "美豆");
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            tv_coin.setText(Html.fromHtml("<font color=\"#ff7f00\">" + context.getResources().getString(R.string.give_meidou) + mSubstring +
                                    "~" + mSubstring1 + "美豆</font>", Html.FROM_HTML_MODE_COMPACT));

                            tv_yield.setText(Html.fromHtml("<font color=\"#ff4c4c\">" + context.getResources().getString(R.string.more_give) + DataUtil.multiplys(goodsInfo.getFloorprice(), "0.05", 2) + "~"
                                    + DataUtil.multiplys(goodsInfo.getPeakprice(), "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));
                        } else {
                            tv_coin.setText(Html.fromHtml("<font color=\"#ff7f00\">" + context.getResources().getString(R.string.give_meidou) + mSubstring +
                                    "~" + mSubstring1 + "美豆</font>"));

                            tv_yield.setText(Html.fromHtml("<font color=\"#ff4c4c\">" + context.getResources().getString(R.string.more_give) + DataUtil.multiplys(goodsInfo.getFloorprice(), "0.05", 2) + "~"
                                    + DataUtil.multiplys(goodsInfo.getPeakprice(), "0.05", 2) + "红豆</font>"));
                        }
                       /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            tv_coin.setText(Html.fromHtml("<font color=\"#ff7f00\">" + context.getResources().getString(R.string.give_meidou) + mSubstring +
                                    "美豆<br/></font><font color=\"#ff4c4c\">"+context.getResources().getString(R.string.more_give) + DataUtil.multiplys(goodsInfo.getFloorprice(), "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));

                            tv_yield.setText(Html.fromHtml("<font color=\"#ff7f00\"> ~ " + mSubstring1 +
                                    "美豆<br/></font><font color=\"#ff4c4c\">" +context.getResources().getString(R.string.more_give)+ DataUtil.multiplys(goodsInfo.getPeakprice(), "0.05", 2) + "红豆</font>", Html.FROM_HTML_MODE_COMPACT));
                        } else {
                            tv_coin.setText(Html.fromHtml("<font color=\"#ff7f00\">" + context.getResources().getString(R.string.give_meidou) + mSubstring +
                                    "美豆<br/></font><font color=\"#ff4c4c\">"+context.getResources().getString(R.string.more_give) + DataUtil.multiplys(goodsInfo.getFloorprice(), "0.05", 2) + "红豆</font>"));

                            tv_yield.setText(Html.fromHtml("<font color=\"#ff7f00\"> ~ " + mSubstring1 +
                                    "美豆<br/></font><font color=\"#ff4c4c\">"+context.getResources().getString(R.string.more_give) + DataUtil.multiplys(goodsInfo.getPeakprice(), "0.05", 2) + "红豆</font>"));
                        }*/
                    }
                }
                break;
//            case 2:
//                if (goodsInfo.getFloorprice().equals(goodsInfo.getPeakprice())) {
//                    tv_coin.setText("立即赠 " + DataUtil.multiplys(goodsInfo.getFloorprice(), "2") + " 美豆");
//                } else {
//                    tv_coin.setText("立即赠" + DataUtil.multiplys(goodsInfo.getFloorprice(), "2") + "美豆 ~ " + DataUtil.multiplys(goodsInfo.getPeakprice(), "2") + "美豆");
//                }
//                break;
            case 3:
                if (TextUtils.isEmpty(goodsInfo.getFloorprice())) {
                    tv_coin.setText("");
                    tv_yield.setText("");
                } else {
                    tv_yield.setTextColor(context.getResources().getColor(R.color.title_red));
                    tv_coin.setTextColor(context.getResources().getColor(R.color.title_red));
                    if (CommonTool.getWhole(DataUtil.multiplys(goodsInfo.getFloorprice(),Constants.REDBEAN_RATE,4)).equals(CommonTool.getWhole(DataUtil.multiplys(goodsInfo.getPeakprice(),Constants.REDBEAN_RATE,4)))) {
                        if (DataUtil.moreThanZero(CommonTool.getWhole(DataUtil.multiplys(goodsInfo.getFloorprice(), Constants.REDBEAN_RATE, 4)))){
                            tv_yield.setText(getString(R.string.award_hongdou) + CommonTool.getWhole(DataUtil.multiplys(goodsInfo.getFloorprice(), Constants.REDBEAN_RATE, 4)) + "红豆");
                        }else
                            tv_yield.setText("");

                    } else {
                        tv_yield.setText(getString(R.string.award_hongdou) +
                                CommonTool.getWhole(DataUtil.multiplys(goodsInfo.getFloorprice(), Constants.REDBEAN_RATE, 4)) + "红豆 ~ " + CommonTool.getWhole(DataUtil.multiplys(goodsInfo.getPeakprice(), Constants.REDBEAN_RATE, 4)) + "红豆");
                    }
                    if (goodsInfo.getFloorprice().equals(goodsInfo.getPeakprice())){
                        tv_coin.setText(getResources().getString(R.string.goldenDesc) + goodsInfo.getFloorprice() + "元消费红包");
                    }else {
                        tv_coin.setText(getResources().getString(R.string.goldenDesc) + goodsInfo.getFloorprice() + "元 ~ " + goodsInfo.getPeakprice() + "元消费红包");
                    }

                }
                break;
        }
        switch (goodsInfo.getGetermethod()) {
            case "1":  //邮寄
                DataUtil.noSelect(context, type1, tv1, tv11);
                DataUtil.noSelect(context, type2, tv2, tv22);
                DataUtil.canSelect(context, type3, tv3, tv33);
                stateType3 = false;
                type3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType3 = !stateType3;
                        if (stateType3) {
                            DataUtil.isSelect(context, type3, tv3, tv33);
                        } else {
                            DataUtil.canSelect(context, type3, tv3, tv33);
                        }
                    }
                });
                break;
            case "2":   //自提
                DataUtil.noSelect(context, type1, tv1, tv11);
                DataUtil.canSelect(context, type2, tv2, tv22);
                DataUtil.noSelect(context, type3, tv3, tv33);
                stateType2 = false;
                type2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType2 = !stateType2;
                        if (stateType2) {
                            DataUtil.isSelect(context, type2, tv2, tv22);
                        } else {
                            DataUtil.canSelect(context, type2, tv2, tv22);
                        }
                    }
                });
                break;
            case "3":   //邮寄+自提
                DataUtil.noSelect(context, type1, tv1, tv11);
                DataUtil.canSelect(context, type2, tv2, tv22);
                DataUtil.canSelect(context, type3, tv3, tv33);
                stateType2 = false;
                type2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType2 = !stateType2;
                        stateType3 = false;
                        if (stateType2) {
                            DataUtil.isSelect(context, type2, tv2, tv22);
                        } else {
                            DataUtil.canSelect(context, type2, tv2, tv22);
                        }
                        DataUtil.canSelect(context, type3, tv3, tv33);
                    }
                });
                stateType3 = false;
                type3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType3 = !stateType3;
                        stateType2 = false;
                        if (stateType3) {
                            DataUtil.isSelect(context, type3, tv3, tv33);
                        } else {
                            DataUtil.canSelect(context, type3, tv3, tv33);
                        }
                        DataUtil.canSelect(context, type2, tv2, tv22);
                    }
                });
                break;
            case "4":  //当面付
                DataUtil.noSelect(context, type2, tv2, tv22);
                DataUtil.noSelect(context, type3, tv3, tv33);
                stateType1 = false;
                type1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType1 = !stateType1;
                        if (stateType1) {
                            DataUtil.isSelect(context, type1, tv1, tv11);
                        } else {
                            DataUtil.canSelect(context, type1, tv1, tv11);
                        }
                    }
                });
                break;
            case "5":   //邮寄+当面付
                DataUtil.canSelect(context, type1, tv1, tv11);
                DataUtil.noSelect(context, type2, tv2, tv22);
                DataUtil.canSelect(context, type3, tv3, tv33);
                stateType1 = false;
                type1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType1 = !stateType1;
                        stateType3 = false;
                        if (stateType1) {
                            DataUtil.isSelect(context, type1, tv1, tv11);
                        } else {
                            DataUtil.canSelect(context, type1, tv1, tv11);
                        }
                        DataUtil.canSelect(context, type3, tv3, tv33);
                    }
                });
                stateType3 = false;
                type3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType3 = !stateType3;
                        stateType1 = false;
                        tvAddSure_attr.setBackgroundResource(R.drawable.shape2);
                        tvAddSure_attr.setTextColor(context.getResources().getColor(R.color.white));
                        if (stateType3) {
                            DataUtil.isSelect(context, type3, tv3, tv33);
                        } else {
                            DataUtil.canSelect(context, type3, tv3, tv33);
                        }
                        DataUtil.canSelect(context, type1, tv1, tv11);
                    }
                });
                break;
            case "6":   //自提+当面付
                DataUtil.canSelect(context, type1, tv1, tv11);
                DataUtil.canSelect(context, type2, tv2, tv22);
                DataUtil.noSelect(context, type3, tv3, tv33);
                stateType1 = false;
                type1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType1 = !stateType1;
                        stateType2 = false;
                        if (stateType1) {
                            DataUtil.isSelect(context, type1, tv1, tv11);
                        } else {
                            DataUtil.canSelect(context, type1, tv1, tv11);
                        }
                        DataUtil.canSelect(context, type2, tv2, tv22);
                    }
                });
                stateType2 = false;
                type2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType2 = !stateType2;
                        stateType1 = false;
                        if (stateType2) {
                            DataUtil.isSelect(context, type2, tv2, tv22);
                        } else {
                            DataUtil.canSelect(context, type2, tv2, tv22);
                        }
                        DataUtil.canSelect(context, type1, tv1, tv11);
                    }
                });
                break;
            case "7":  //邮寄+自提+当面付
                DataUtil.canSelect(context, type2, tv2, tv22);
                DataUtil.canSelect(context, type3, tv3, tv33);
                stateType1 = false;
                DataUtil.canSelect(context, type1, tv1, tv11);
                type1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType1 = !stateType1;
                        stateType2 = false;
                        stateType3 = false;
                        if (stateType1) {
                            DataUtil.isSelect(context, type1, tv1, tv11);
                        } else {
                            DataUtil.canSelect(context, type1, tv1, tv11);
                        }
                        DataUtil.canSelect(context, type2, tv2, tv22);
                        DataUtil.canSelect(context, type3, tv3, tv33);
                    }
                });
                stateType2 = false;
                type2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType2 = !stateType2;
                        stateType1 = false;
                        stateType3 = false;
                        if (stateType2) {
                            DataUtil.isSelect(context, type2, tv2, tv22);
                        } else {
                            DataUtil.canSelect(context, type2, tv2, tv22);
                        }
                        DataUtil.canSelect(context, type1, tv1, tv11);
                        DataUtil.canSelect(context, type3, tv3, tv33);
                    }
                });
                stateType3 = false;
                type3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        stateType3 = !stateType3;
                        stateType1 = false;
                        stateType2 = false;
                        if (stateType3) {
                            DataUtil.isSelect(context, type3, tv3, tv33);
                        } else {
                            DataUtil.canSelect(context, type3, tv3, tv33);
                        }
                        DataUtil.canSelect(context, type1, tv1, tv11);
                        DataUtil.canSelect(context, type2, tv2, tv22);
                    }
                });
                break;
        }

        tvSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = etNum.getText().toString().trim();
                int num = Integer.parseInt(trim);
                if (num > 1) {
                    num--;
                } else {
                    showShortToast("最少购买一件");
                }
                etNum.setText(String.valueOf(num));
            }
        });
        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = etNum.getText().toString().trim();
                int num = Integer.parseInt(trim);
                if (num <= 100) {
                    num++;
                } else {
                    showShortToast("购买数量不能大于100");
                }
                etNum.setText(String.valueOf(num));
            }
        });
        //加购物车
        tvAddSure_attr.setOnClickListener(new View.OnClickListener() {
            private boolean containsAll;
            private boolean b;

            @Override
            public void onClick(View view) {
                if (stateType1 || stateType2 || stateType3) {
                    List<String> attrIdList = new ArrayList<String>();
                    List<String> keySelect = new ArrayList<String>();
                    String jsonAttrId = "[";
                    for (String attr : selectAttrMap.keySet()) {
                        AttrItemBean s = selectAttrMap.get(attr);
                        keySelect.add(attr);
                        attrIdList.add(s.getAttrId());
                        jsonAttrId += "\"" + s.getAttrId() + "\",";
                    }
                    String json = jsonAttrId.substring(0, jsonAttrId.length() - 1) + "]";
                    if (allList != null && allList.size() > 0) {
                        for (int i = 0; i < allList.size(); i++) {
                            AttrsSelect attrsSelect = allList.get(i);
                            Map<String, List<String>> map = attrsSelect.getItemMaps();
                            List<String> mapList = new ArrayList<String>();
                            List<String> mapValue = new ArrayList<String>();
                            for (String attr2 : map.keySet()) {
                                mapList.add(attr2);
                                List<String> list = map.get(attr2);
                                mapValue.addAll(list);
                            }
                            b = DataUtil.equalList(keySelect, mapList);
                            containsAll = mapValue.containsAll(attrIdList);
                            if (b && containsAll) {
                                String trim = tvInventory.getText().toString().trim();
                                String substring = trim.substring(trim.indexOf(":") + 1, trim.length() - 1);
                                if (DataUtil.moreThanZero(substring)) {
                                    Map<String, String> netMap = new HashMap<>();
                                    netMap.put("goodsid", attrsSelect.getGoodsid());
                                    netMap.put("shopid", goodsInfo.getSid());
                                    netMap.put("goodsnum", etNum.getText().toString().trim());
                                    netMap.put("collectionid", attrsSelect.getId());
                                    if (stateType2) {
                                        netMap.put("getermethod", "2");
                                    } else if (stateType3) {
                                        netMap.put("getermethod", "1");
                                    } else if (stateType1) {
                                        netMap.put("getermethod", "4");
                                    }
                                    netMap.put("attrlist", json);
                                    type = "goShoppingCart";
                                    getServer(Url.MALL_ADDTO_CART, netMap, "", false, null, "post");
                                } else {
                                    showShortToast("库存不足,无法加入购物车");
                                }
                                return;
                            }
                        }
                    }
                    if (!(b && containsAll)) {
                        showShortToast("请您选择完整的商品属性");
                    }
                } else {
                    showShortToast("请选择收货方式");
                }
            }
        });

        //立即购买
        tvSure_attr.setOnClickListener(new View.OnClickListener() {
            private boolean containsAll;   //进入确认支付界面
            private boolean b;

            @Override
            public void onClick(View view) {
                if (stateType1 || stateType2 || stateType3) {
                    List<String> attrIdList = new ArrayList<>();
                    List<String> keySelect = new ArrayList<>();
                    List<String> itemAttrs = new ArrayList<>();
                    String jsonAttrId = "[";     //  {"password":"1234","username":"cxl"}
                    for (String attr : selectAttrMap.keySet()) {
                        AttrItemBean s = selectAttrMap.get(attr);
                        keySelect.add(attr);
                        attrIdList.add(s.getAttrId());
                        itemAttrs.add(s.getName());
                        jsonAttrId = jsonAttrId + "\"" + s.getAttrId() + "\",";
                    }
                    String json = jsonAttrId.substring(0, jsonAttrId.length() - 1) + "]";
                    if (allList != null && allList.size() > 0) {
                        for (int i = 0; i < allList.size(); i++) {
                            AttrsSelect attrsSelect = allList.get(i);
                            Map<String, List<String>> map = attrsSelect.getItemMaps();
                            List<String> mapList = new ArrayList<>();
                            List<String> mapAttrId = new ArrayList<>();
                            for (String attr2 : map.keySet()) {
                                mapList.add(attr2);
                                List<String> list = map.get(attr2);
                                mapAttrId.addAll(list);
                            }
                            b = DataUtil.equalList(keySelect, mapList);
                            containsAll = mapAttrId.containsAll(attrIdList);
                            if (b && containsAll) {
                                String trim = tvInventory.getText().toString().trim();
                                String substring = trim.substring(trim.indexOf(":") + 1, trim.length() - 1);
                                if (DataUtil.moreThanZero(substring)) {
                                    popupWindow.dismiss();
                                    attrsSelect.setName(goodsInfo.getName());
                                    attrsSelect.setGoodsnum(etNum.getText().toString().trim());
                                    attrsSelect.setPostage(goodsInfo.getPostage());
                                    attrsSelect.setGoodstype(goodsInfo.getGoodstype());
                                    attrsSelect.setGetermethod(goodsInfo.getGetermethod());
                                    attrsSelect.setAttrlist(json);
                                    attrsSelect.setItemGoodAttrs(itemAttrs);
                                    Intent intent = new Intent(context, ApplyRewardActivity.class);
                                    intent.putExtra("attrs", attrsSelect);
                                    if (stateType2) {
                                        intent.putExtra("post", 0);  // 自提
                                    } else if (stateType3) {
                                        intent.putExtra("post", 1);  // 邮寄
                                    } else if (stateType1) {
                                        intent.putExtra("post", 2);  // 同城免邮
                                    }
                                    startActivity(intent);
                                    return;
                                } else {
                                    showShortToast("库存不足,无法支付");
                                }
                            }
                        }
                    }
                    if (!(b && containsAll)) {
                        showShortToast("请把该商品属性选完整");
                    }
                } /*else if (stateType1) {            // 当面付
                    List<String> attrIdList = new ArrayList<>();
                    List<String> keySelect = new ArrayList<>();
                    List<String> itemAttr = new ArrayList<>();
                    String jsonAttrId = "[";     //["mar677459ffd105463ad","mar541359ffd15233154"]
                    for (String attr : selectAttrMap.keySet()) {
                        AttrItemBean s = selectAttrMap.get(attr);
                        keySelect.add(attr);
                        attrIdList.add(s.getAttrId());
                        itemAttr.add(s.getName());
                        jsonAttrId = jsonAttrId + "\"" + s.getAttrId() + "\",";
                    }
                    String json = jsonAttrId.substring(0, jsonAttrId.length() - 1) + "]";
                    if (allList != null && allList.size() > 0) {
                        for (int i = 0; i < allList.size(); i++) {
                            AttrsSelect attrsSelect = allList.get(i);
                            Map<String, List<String>> map = attrsSelect.getItemMaps();
                            List<String> mapList = new ArrayList<>();
                            List<String> mapAttrId = new ArrayList<>();
                            for (String attr2 : map.keySet()) {
                                mapList.add(attr2);
                                List<String> list = map.get(attr2);
                                mapAttrId.addAll(list);
                            }
                            b = DataUtil.equalList(keySelect, mapList);
                            containsAll = mapAttrId.containsAll(attrIdList);
                            if (b && containsAll) {
                                String trim = tvInventory.getText().toString().trim();
                                String substring = trim.substring(trim.indexOf(":") + 1, trim.length() - 1);
                                if (DataUtil.moreThanZero(substring)) {
                                    popupWindow.dismiss();
                                    attrsSelect.setName(goodsInfo.getName());
                                    attrsSelect.setGoodsnum(etNum.getText().toString().trim());
                                    attrsSelect.setPostage(goodsInfo.getPostage());
                                    attrsSelect.setGoodstype(goodsInfo.getGoodstype());
                                    attrsSelect.setGetermethod(goodsInfo.getGetermethod());
                                    attrsSelect.setItemGoodAttrs(itemAttr);
                                    attrsSelect.setAttrlist(json);
                                    Intent intent = new Intent(context, PresentPayActivity.class);
                                    intent.putExtra("attrs", attrsSelect);
                                    startActivity(intent);
                                } else {
                                    showShortToast("库存不足,无法支付");
                                }
                                return;
                            }
                        }
                    }
                    if (!(b && containsAll)) {
                        showShortToast("请把该商品属性选完整");
                    }
                }*/ else {
                    showShortToast("请选择支付方式");
                }

            }
        });

        if (attr != null && !"".equals(attr)) {
            Iterator<String> keys = attr.keys();
            List<String> keyList = new ArrayList<>();
            itemAttrList = new ArrayList<>();
            mapAllAttrs = new HashMap<>();
            while (keys.hasNext()) {
                String next = keys.next();
                keyList.add(next);
                JSONArray jsonArray = attr.optJSONArray(next); //  [ ["十边形","att2929593f9c024ddd5"], ["六边形","att7364593f9960eb35b"] ]
                List<AttrItemBean> itemList = new ArrayList<>();
                for (int k = 0; k < jsonArray.length(); k++) {
                    try {
                        JSONArray jsonAllItemArray = (JSONArray) jsonArray.get(k);
                        AttrItemBean attrItemBean = new AttrItemBean();
                        for (int l = 0; l < jsonAllItemArray.length(); l++) {
                            if (l == 0) {
                                String attrName = (String) jsonAllItemArray.get(l);
                                attrItemBean.setName(attrName);
                            } else if (l == 1) {
                                String attrId = (String) jsonAllItemArray.get(l);
                                attrItemBean.setAttrId(attrId);
                            }
                            attrItemBean.setStates("1");
                        }
                        itemList.add(attrItemBean);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                itemAttrList.add(itemList);
                mapAllAttrs.put(next, itemList);
            }
            if (keyList != null && keyList.size() > 0 && douGoodsData.getGoodsAttrCollection() != null &&
                    douGoodsData.getGoodsAttrCollection().size() > 0) {
                coinPostGoodAttrAdapter = new CoinPostGoodAttrAdapter(context, handler, keyList, itemAttrList);
                lvList.setAdapter(coinPostGoodAttrAdapter);
                coinPostGoodAttrAdapter.notifyDataSetChanged();
            }
        }
        //消失
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    isRemove = false;
                    popupWindow = null;
                }
            }
        });
        if (!popupWindow.isShowing()) {
            isRemove = false;
        }
        popupWindow_view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int[] location = new int[2];
        linearBottom.getLocationOnScreen(location);
        popupWindow.showAtLocation(linearBottom, Gravity.BOTTOM, location[0], location[1] - popupWindow.getHeight());
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}